#include "logwidget.h"
#include <QTextEdit>
#include <QLineEdit>
#include <QPushButton>
#include <QComboBox>
#include <QCheckBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QFileDialog>
#include <QSettings>
#include <QTextStream>
#include <QClipboard>
#include <QApplication>
#include <QRegularExpressionValidator>

LogWidget::LogWidget(QWidget *parent)
    : QWidget(parent)
    , currentLevel(Info)
    , messageCount(0)
{
    setupUI();
    loadSettings();
    
    // 添加一些示例日志消息
    logInfo(tr("日志系统已初始化"));
    logDebug(tr("这是调试信息"));
    logWarning(tr("这是警告信息"));
    logError(tr("这是错误信息"));
}

LogWidget::~LogWidget()
{
    saveSettings();
}

void LogWidget::logMessage(LogLevel level, const QString &message)
{
    // 检查日志级别过滤
    if (level < currentLevel)
        return;
        
    // 格式化消息
    QString formattedMessage = formatMessage(level, message);
    
    // 添加到文本编辑器
    logTextEdit->append(formattedMessage);
    
    // 更新消息计数
    messageCount++;
    
    // 自动滚动到底部
    if (autoScrollCheckBox->isChecked()) {
        logTextEdit->moveCursor(QTextCursor::End);
    }
}

void LogWidget::logDebug(const QString &message)
{
    logMessage(Debug, message);
}

void LogWidget::logInfo(const QString &message)
{
    logMessage(Info, message);
}

void LogWidget::logWarning(const QString &message)
{
    logMessage(Warning, message);
}

void LogWidget::logError(const QString &message)
{
    logMessage(Error, message);
}

void LogWidget::clearLog()
{
    logTextEdit->clear();
    messageCount = 0;
}

void LogWidget::filterChanged()
{
    currentLevel = static_cast<LogLevel>(levelComboBox->currentIndex());
}

void LogWidget::copySelected()
{
    QString selectedText = logTextEdit->textCursor().selectedText();
    if (!selectedText.isEmpty()) {
        QApplication::clipboard()->setText(selectedText);
    }
}

void LogWidget::saveLog()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("保存日志"), 
                                                    "remotemaster.log", 
                                                    tr("日志文件 (*.log);;所有文件 (*)"));
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&file);
            out << logTextEdit->toPlainText();
            file.close();
        }
    }
}

void LogWidget::setupUI()
{
    // 创建文本编辑器
    logTextEdit = new QTextEdit;
    logTextEdit->setReadOnly(true);
    logTextEdit->setLineWrapMode(QTextEdit::NoWrap);
    
    // 创建过滤输入框
    filterLineEdit = new QLineEdit;
    filterLineEdit->setPlaceholderText(tr("输入过滤文本"));
    
    // 创建级别组合框
    levelComboBox = new QComboBox;
    levelComboBox->addItem(tr("调试"));
    levelComboBox->addItem(tr("信息"));
    levelComboBox->addItem(tr("警告"));
    levelComboBox->addItem(tr("错误"));
    levelComboBox->setCurrentIndex(currentLevel);
    connect(levelComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &LogWidget::filterChanged);
    
    // 创建复选框
    autoScrollCheckBox = new QCheckBox(tr("自动滚动"));
    autoScrollCheckBox->setChecked(true);
    
    // 创建按钮
    clearButton = new QPushButton(tr("清空"));
    connect(clearButton, &QPushButton::clicked, this, &LogWidget::clearLog);
    
    copyButton = new QPushButton(tr("复制"));
    connect(copyButton, &QPushButton::clicked, this, &LogWidget::copySelected);
    
    saveButton = new QPushButton(tr("保存"));
    connect(saveButton, &QPushButton::clicked, this, &LogWidget::saveLog);
    
    // 控制布局
    controlLayout = new QHBoxLayout;
    controlLayout->addWidget(new QLabel(tr("级别:")));
    controlLayout->addWidget(levelComboBox);
    controlLayout->addSpacing(10);
    controlLayout->addWidget(autoScrollCheckBox);
    controlLayout->addStretch();
    controlLayout->addWidget(clearButton);
    controlLayout->addWidget(copyButton);
    controlLayout->addWidget(saveButton);
    
    // 主布局
    mainLayout = new QVBoxLayout;
    mainLayout->addLayout(controlLayout);
    mainLayout->addWidget(logTextEdit);
    setLayout(mainLayout);
}

void LogWidget::loadSettings()
{
    QSettings settings;
    
    currentLevel = static_cast<LogLevel>(
        settings.value("logwidget/level", Info).toInt());
    levelComboBox->setCurrentIndex(currentLevel);
    
    autoScrollCheckBox->setChecked(
        settings.value("logwidget/autoscroll", true).toBool());
}

void LogWidget::saveSettings()
{
    QSettings settings;
    
    settings.setValue("logwidget/level", currentLevel);
    settings.setValue("logwidget/autoscroll", autoScrollCheckBox->isChecked());
}

QString LogWidget::levelToString(LogLevel level) const
{
    switch (level) {
    case Debug:
        return "DEBUG";
    case Info:
        return "INFO";
    case Warning:
        return "WARN";
    case Error:
        return "ERROR";
    default:
        return "UNKNOWN";
    }
}

QString LogWidget::formatMessage(LogLevel level, const QString &message) const
{
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString levelStr = levelToString(level);
    return QString("[%1] [%2] %3").arg(timestamp, levelStr, message);
}